//
//  CZOauthViewController.swift
//  weibo10
//
//  Created by apple on 16/5/13.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZOauthViewController: UIViewController
{
    
    override func loadView() {
        view = webView
       webView.delegate = self
    }
    
    

    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        self.view.backgroundColor = GlobalBKGColor
        
        //设置导航栏左边按钮
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        //右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        //title
        navigationItem.title = "登录"
        
        
        //用webView加载登录界面
        
        let urlString = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
       
    SVProgressHUD.showWithStatus("正在加载")
        
    }
    //按钮点击事件
   @objc private func autoFill()
    {
    
    let jsString = "document.getElementById('userId').value='15992695908';document.getElementById('passwd').value='win7758521270302';"
    
        //使用webView执行JS代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    //取消
  @objc  private func close()
    {
    SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    
    //懒加载
    private lazy var webView:UIWebView = UIWebView()
}



extension CZOauthViewController:UIWebViewDelegate
{
//WebView加载完成调用
    func webViewDidFinishLoad(webView: UIWebView)
    {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        let url = request.URL!
        
//        CZPrint(items: "request: \(url.absoluteString)")
        
        if !url.absoluteString.hasPrefix(redirect_uri)
        {
        //只要不是授权回调地址，是新浪界面，就让它去加载
            return true
        
        }else
        {
        //授权回调地址,点击取消或授权，不让它加载，我们自己做操做
            let query = url.query!
            
//            CZPrint(items: "query: \(query)")
           let codeString = "code="
            
            if query.hasPrefix(codeString)
            {
                // 如果query 是以 code=开头表示点击的授权按钮
                // 从query中截取code的值,substringFromIndex从指定位置截取到最后
                
                let code = (query as NSString).substringFromIndex(codeString.characters.count)
                CZPrint(items: "code: \(code)")
                
                
                //加载AccessToken,字典转模型，模型保存到沙盒
                CZUserAccountViewModel.sharedInstance.loadAccessToken(code, callback: { (error) -> () in
                    
                    if error != nil
                    {
                    //出现错误
                        CZPrint(items: "出现了错误: \(error)")
                        SVProgressHUD.showErrorWithStatus("网络不给力哟")
                        //延迟一秒关闭
                        // 延迟一秒关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                    } else {
                        // 登录成功,没有错误
                        self.close()
                        
                        // 跳转到CZWelcomeViewCotroller
                        // 调用AppDelegate的switchRootViewContriller
                        let appDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
                        appDelegate.switchRootViewController(CZWelcomeViewController())
                    }
                })
            } else {
                // query不是以code=开头,点击的是取消按钮
                close()
            }
            
            return false
        }
    }
}



